package com.itrident.loader.imlp;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.CustomLiveTemplateBase;
import com.intellij.codeInsight.template.impl.CustomLiveTemplateLookupElement;
import com.intellij.ide.fileTemplates.impl.UrlUtil;
import com.itrident.loader.AbstractLoader;
import com.itrident.loader.element.Element;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

/**
 * @author cxx
 * @create 2020-12-29 9:54
 **/
public class GenLoader extends AbstractLoader {

    /**
     * 所有的节点
     */
    private static final List<Element> ALL_ELEMENT = new ArrayList<> (10);

    protected GenLoader(CustomLiveTemplateBase ctb) {
        super (ctb);
    }

    @Override
    public List<LookupElement> load(String prefix) {
        return loadLookupElements(prefix);
    }

    private List<LookupElement> loadLookupElements(String prefix) {
        List<Element> elements = loadElements (prefix);
        List<LookupElement> lookupElements = new ArrayList<> (elements.size ());
        for (Element e : elements) {
            CustomLiveTemplateLookupElement lookupElement = new CustomLiveTemplateLookupElement (ctb, e.getText ()
                    , e.getItem (), e.getDesc (), false, true);
            lookupElements.add (lookupElement);
        }
        return lookupElements;
    }

    private List<Element> loadElements(String prefix) {
        initElement();
        return matcher(prefix);
    }

    private List<Element> matcher(String prefix) {
        List<Element> elements = new ArrayList<> (ALL_ELEMENT.size ());
        for (Element element : ALL_ELEMENT) {
            String item = element.getItem ();
            if (item.startsWith (prefix)) {
                elements.add (element);
            }
        }
        return elements;
    }


    private static synchronized void initElement(){
        try {
            if(!ALL_ELEMENT.isEmpty ()){
                return;
            }
            String text = UrlUtil.loadText (GenLoader.class.getResource ("/element/gen.properties"));
            Properties properties = new Properties ();
            properties.load (new StringReader (text));
            Set<String> keys = properties.stringPropertyNames ();
            for (String key : keys) {
                String val = properties.getProperty (key);
                ALL_ELEMENT.add (new Element (val, key,"bean properties"));
            }
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
